package com.ark.cloud.dataservices.auth.interceptor;

/**
 * Copyright(c): 2021 Cloud-Ark Inc.
 * Author(s): Ma Wei (mawei@cloud-ark.com)
 */

import com.ark.cloud.dataservices.auth.service.IAuthenticationService;
import com.ark.cloud.dataservices.config.JwtConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * JWT登录授权过滤器
 */
@Slf4j
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private JwtConfig jwtConfig;

    @Value("${jwt.header}")
    private String tokenHeader;

    @Autowired
    private IAuthenticationService authenticationService;

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain chain) throws ServletException, IOException {
        String requestURI = request.getRequestURI();
        // todo 开放部分 URL。不知为何，添加到 SecurityConfig 中的配置没有生效
        if (!requestURI.startsWith("/auth") && !requestURI.startsWith("/dataservice")) {
            //获取请求头
            String authToken = request.getHeader(this.tokenHeader);
            if (StringUtils.isNotBlank(authToken)) {
                //根据token获取用户名
                String username = jwtConfig.getUserNameFromToken(authToken);
                log.info("用户名: username:{}", username);
                UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
                if (jwtConfig.validateToken(authToken, userDetails)) {
                    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                    log.info("authenticated user:{}", username);
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                    //访问资源权限校验
                    authenticationService.authenticate(request, response, authToken, request.getRequestURI(), request.getMethod());
                }
            }
        }
        //放行
        chain.doFilter(request, response);
    }
}